<template>
  <div>
    <a-row :gutter="12">
      <a-col :md="6" >
        <a-button @click="toggleMode">{{ this.day.text }}</a-button>
        <a-button @click="editMode">{{ this.edit.text }}</a-button>
      </a-col>
    </a-row>
    <div ref="dhxgantt" class='left-container'></div>
  </div>

</template>

<script>
import {gantt} from 'dhtmlx-gantt';
export default {
  name: 'ganttTable',
  props: {
    startTIme: {
      type: String,
      default: ""
    },
    endTime: {
      type: String,
      default: ""
    },
    data:{
      type: Array,
      default: function(){
        return []
      }
    }
  },
  data(){
    return {
      tasks: {
        data: [],
        links: []
      },
      localData: this.data,
      day: {
        text: '切换到天模式预览',
        enable: false
      },
      edit: {
        text: '切换到编辑预览',
        enable: false
      }
    }
  },
  watch:{
    data(val,oldval){
      console.log(val,oldval,'watch')
      this.localData = val
      this.refresh()
    }
  },
  methods: {
    hide() {
      console.log(111);
      this.visible = false;
    },
    getGantt(){
      // const gantt = gantt.getGanttInstance()
      gantt.i18n.setLocale('cn')
      // 设置时间格式
      gantt.config.task_date = '%Y-%m-%d %H:%i'
      gantt.config.date_format = '%Y-%m-%d %H:%i'
      gantt.templates.task_date = function (date) {
        return gantt.date.date_to_str(gantt.config.task_date)(date)
      }

      gantt.config.auto_scheduling = false
      gantt.config.auto_scheduling_strict = false
      gantt.config.auto_scheduling_compatibility = false
      gantt.config.drag_progress = false

      // 把任务或者连线拖拽到浏览器屏幕外时，自动触发滚动效果，相当于拖动滚动条
      gantt.config.autoscroll = true

      gantt.config.autofit = true

      gantt.config.fit_tasks = true

      // 是否显示依赖连线
      gantt.config.show_links = false

      // 将任务开始时间和结束时间自动“四舍五入”, 从而对齐坐标轴刻度
      gantt.config.round_dnd_dates = false

      // 左侧树型结构调整时，可以任意拖动任务到任意节点下
      gantt.config.order_branch = true
      gantt.config.order_branch_free = false

      gantt.config.placeholder_task = true

      gantt.config.open_split_tasks = true
      gantt.config.min_duration = 1000 * 60

      // 任务的时间间隔
      gantt.config.time_step = 1
      // 增加可拖动 插件
      gantt.plugins({
        // 任务时间缩放
        auto_scheduling: true,
        // 任务时间拖动
        drag_timeline: true,
        // 快速信息扩展
        quick_info: true
      })

      // 设置展示的列
      gantt.config.columns = [
        { name: 'text', label: '产线名称', width: 200, tree: true },
        { name: 'start_date',
          label: '开始时间',
          width: 200,
          template: function (obj) {
            return gantt.date.date_to_str(gantt.config.task_date)(obj.start_date)
          } },
        { name: 'product_count', label: '生产数量' }
      ]

      gantt.createDataProcessor((entity,action,data,id) => {
        console.log(entity,action,data,id,'entity,action,data,id')
        this.$emit(`${entity}-update`,id,action,data)
      });

      // gantt.attachEvent('onTaskClick',(id,e) => {
      //   const task = gantt.getTask(id)
      //   this.$emit("onTaskClick",task)
      // })
      // 修改双击事件的逻辑
      gantt.attachEvent('onTaskDblClick', (id, e) => {
        const task = gantt.getTask(id)
        console.log('onTaskDblClick',task)
        this.$emit("onTaskDblClick",task)
        // if (task.readonly && !task.isParent) {
        //   this.$confirm({
        //     title: '是否要强制关闭任务？',
        //     content: '是否要强制关闭任务',
        //     onOk: () => {
        //       forceClose({
        //         planCode: task.id
        //       }).then(res => {
        //         this.refresh()
        //       })
        //     },
        //     onCancel () {
        //       console.log('Cancel')
        //     }
        //   })
        // }
      })

      // // 甘特图调整时间 的回调
      // gantt.attachEvent('onAfterTaskUpdate', (id, task) => {
      //   // task 有更新就会调用
      //   if (!task.parent || task.readonly) {
      //     // 说明是父任务
      //     return true
      //   }
      //   // // 更新任务的时间
      //   // updateTime({
      //   //   id: task.id,
      //   //   planStartDate: moment(task.start_date).format('YYYY-MM-DD HH:mm:ss'),
      //   //   deviceCode: task.deviceCode
      //   // }).then(res => {
      //   //   return true
      //   // }).catch(err => {
      //   //   this.$message.error(err.msg)
      //   //   return false
      //   // })
      //   return true
      // })


      gantt.templates.progress_text = function (start, end, task) {
        return "<span style='text-align:left;'>" + Math.round(task.progress * 100) + '% </span>'
      }
      // // 修改拖动 甘特图 确定那种类型可以拖动
      // gantt.attachEvent('onBeforeTaskDrag', function (id, mode) {
      //   if (mode === gantt.config.drag_mode.progress) {
      //
      //   } else {
      //     if (mode === gantt.config.drag_mode.move) {
      //     } else if (mode === gantt.config.drag_mode.resize) {
      //       // 移动 任务的长度
      //       return false
      //     }
      //   }
      //   return true
      // })

      // 设置任务的class
      gantt.templates.task_class = function (start, end, task) {
        if (task.isParent) {
          return 'device'
        } else if (task.readonly) {
          return 'normal'
        } else {
          return 'low'
        }
      }

      // 设置任务显示的内容
      gantt.templates.task_text = function (start, end, task) {
        // return `<slot name='taskText'></slot>`
        if (task.isParent) {
          return "<span style='text-align:left;'>" + task.text + '</span>'
        } else {
          return "<span style='text-align:left;'>" + task.text + '-' + task.success_count + '/' + task.product_count + '个 </span>'
        }
      }


      // quickinfo 按钮组件
      gantt.config.quickinfo_buttons = ['edit', 'split', 'release', 'delete']
      gantt.locale.labels['split'] = '拆分'
      gantt.locale.labels['release'] = '发布'
      gantt.locale.labels['delete'] = '删除'

      gantt.locale.labels['edit'] = '修改'

      gantt.$click.buttons.edit = (e, id, trq) => {
        // 修改
        const task = gantt.getTask(e)
        if (task.readonly) {
          this.$message.error('锁定任务不能操作')
          return
        }
      }


      gantt.config.duration_unit = 'hour'

      gantt.config.scale_unit = 'hour'
      gantt.config.date_scale = '%d日%H时'
      // 清除原有信息
      gantt.clearAll()
      this.$nextTick(() => {
        gantt.init(this.$refs.dhxgantt)
      })

      // this.$data.tasks.data = this.localData
      // gantt.parse(this.$data.tasks)
      this.initGanntData()
    },
    // 甘特图初始化数据
    initGanntData () {
      this.$nextTick(() => {
        gantt.clearAll()
        // 数据解析
        gantt.parse(this.$data.tasks)
      })
    },
    toggleMode () {
      this.day.enable = !this.day.enable
      if (this.day.enable) {
        this.day.text = '切换到小时模式预览'
        gantt.config.scale_unit = 'day'
        gantt.config.date_scale = '%F,%d'
        gantt.render()
      } else {
        this.day.text = '切换到天模式预览'
        gantt.config.scale_unit = 'hour'
        gantt.config.date_scale = '%d日%H时'
        gantt.render()
      }
    },
    editMode(){
      this.edit.enable = !this.edit.enable
      if (this.edit.enable) {
        this.edit.text = '切换到预览模式'
        // 增加可拖动 插件
        gantt.config.auto_scheduling = true
        gantt.config.auto_scheduling_strict = true
        gantt.config.auto_scheduling_compatibility = true
        gantt.config.drag_progress = true
        gantt.render()
      } else {
        this.edit.text = '切换编辑模式'
        gantt.config.auto_scheduling = false
        gantt.config.auto_scheduling_strict = false
        gantt.config.auto_scheduling_compatibility = false
        gantt.config.drag_progress = false
        gantt.render()
      }
    },
    refresh(){
      this.$data.tasks.data = this.localData
      gantt.parse(this.$data.tasks)
    }
  },
  mounted(){

  }

}
</script>

<style scoped>
@import "~dhtmlx-gantt/codebase/dhtmlxgantt.css";
.left-container {
  overflow: hidden;
  position: relative;
  height: 90%;
}
</style>